﻿using RabbitMQ_Common;
using System;
using System.Collections.Generic;
using System.Text;

namespace RabbitMQ_Producer.Topic
{
    public class TopicProducer
    {
        public static void SendMessage(string message)
        {
            try
            {
                var connection = RabbitMQHelper.GetConnection();
                var channel = connection.CreateModel();

                //开启发布确认
                channel.ConfirmSelect();
                //声明交换机，topic(路由)模式
                channel.ExchangeDeclare("topic_exchange", "topic", true, false, null);

                //声明队列
                channel.QueueDeclare("topic_queue1", true, false, false, null);
                channel.QueueDeclare("topic_queue2", true, false, false, null);
                channel.QueueDeclare("topic_queue3", true, false, false, null);

                //队列绑定交换机
                channel.QueueBind("topic_queue1", "topic_exchange", "user.insert", null);
                channel.QueueBind("topic_queue2", "topic_exchange", "user.update", null);
                channel.QueueBind("topic_queue3", "topic_exchange", "user.*", null);

                //消息设置
                var properties = channel.CreateBasicProperties();
                //持久化
                properties.Persistent = true;

                var body = Encoding.UTF8.GetBytes(message);
                channel.BasicPublish("topic_exchange", "user.insert", false, properties, body);
                //等待消息确认
                if (channel.WaitForConfirms(new TimeSpan(0, 0, 10)))
                {
                    Console.WriteLine($"TopicProducer SendMessage Success:{message}");
                }
                else
                {
                    Console.WriteLine($"TopicProducer SendMessage WaitForConfirms Failed:{message}");
                }
                channel.Close();
                channel.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine($"TopicProducer SendMessage Failed:{e.Message}");
            }
            
        }
    }
}
